import { defineStore } from 'pinia';
import { getUserDetails, userOnline, userOffline } from '@/service/user/userService';
import useWebSocket from '@/hooks/useWebSocket';

export const useUserStore = defineStore('user', {
  state: () => ({
    isLineIn: false,
    username: '',
    email: '',
    avatar: '',
    bio: '',
    className: '',
    school: ''
  }),
  actions: {
    // 用户上线
    async userLinein() {
      this.isLineIn = true;
      try {
        const userDetails = await getUserDetails();
        console.log(userDetails);
        // 存储用户详情到 state 中
        Object.assign(this, userDetails);
        console.log("获取用户详情成功" + this.username);
        // 通知服务端用户上线
        await userOnline(this.username);
        // 初始化连接
        useWebSocket.init();
      } catch (error) {
        console.error('Error fetching user details:', error);
        this.userLineOut();  // 用户下线
      }
    },
    // 用户下线
    async userLineOut() {
      try {
        await userOffline(this.username);
        this.isLineIn = false;
        this.username = '';  // 清除用户名
        // 关闭连接
        useWebSocket.close();
      } catch (error) {
        console.error('Error during user logout:', error);
      }
    },
  }
});
